import {Collapse, Form, Row, Col, Select, message, Table} from 'antd'
import React, {
	forwardRef,
	useImperativeHandle,
	useEffect,
	useState,
} from 'react'
import type {ColumnsType} from 'antd/es/table'
import moment from 'moment'
import styles from './index.less'
import ParticipantsTable from './ParticipantsTable'
import AttachmentTable from './AttachmentTable'
import {DataSourceType} from '../data.t'
import {
	getStocktakeList,
	stocktakeDefinitionList,
} from '@/service/storage/assetInventoryPlan'

const {Panel} = Collapse

type PropsType = {
	dictData?: any
	dataSource?: any
	enclosureList?: any[]
	startDate: any
}

const addPlan = (props: PropsType, ref: any) => {
	const {startDate} = props
	const [form] = Form.useForm()
	// 选择的列表数据
	const [dataList, setDataList] = useState<any>([])
	const [stocktakeList, setStocktakeList] = useState<any>([])
	const [attachmentData, setAttachmentData] = useState<
		readonly DataSourceType[]
	>([])
	const [columns, setColumns] = useState<ColumnsType<any>>([])
	const [planId, setPlanId] = useState('')
	const [loading, setLoading] = useState(false)
	const [dataSource, setDataSource] = useState<any[]>([])

	useEffect(() => {
		if (planId) {
			// 获取盘点表
			setLoading(true)
			stocktakeDefinitionList({
				id: planId,
			})
				.then((res: any) => {
					if (res?.success) {
						const arr: any = []
						const {header, contents} = res.data
						const newColumns: any[] = header.map((value: any) => ({
							title: value,
							dataIndex: value,
							align: 'center',
							width: 150,
						}))
						setColumns(newColumns)
						contents?.forEach((item: any[]) => {
							const newData: any = {}
							item?.forEach((items, index) => {
								newData[header[index]] = items
							})
							arr.push(newData)
						})
						setDataSource(arr)
						setLoading(false)
					} else {
						setLoading(false)
					}
				})
				.catch((err) => {
					setDataSource([])
					message.error(err)
					setLoading(false)
				})
		}
	}, [planId])

	// 盘点表数据需小于计划开始时间
	useEffect(() => {
		if (startDate) {
			/** 获取盘点表列表 */
			getStocktakeList({status: 1})
				.then((res: any) => {
					if (res?.success) {
						const newData = res?.data?.filter(
							(item: {generateTime: moment.MomentInput}) =>
								moment(item?.generateTime) < startDate,
						)
						setStocktakeList(newData)
					}
				})
				.catch((err) => {
					message.error(err)
				})
			form?.setFieldsValue({
				stocktakeId: undefined,
				stocktakeType: '自动带出',
			})
			setPlanId('')
			setDataSource([])
		}
	}, [startDate])

	useEffect(() => {
		form?.setFieldsValue({stocktakeType: '自动带出'})
	}, [])

	const customizeHeader = (value: string) => (
		<div>
			<div className={styles.tip} />
			{value}
		</div>
	)

	const onSubmit = async () => {
		const value = await form?.validateFields()
		const annexList = attachmentData?.map((item) => ({
			name: item?.name,
			url: item?.url,
		}))
		const personList = dataList?.map(
			(item: {userId: number; orgId: number}) => ({
				userId: item?.userId,
				orgId: item?.orgId,
			}),
		)
		const newData = {
			annexList,
			personList,
			stocktakeId: value?.stocktakeId,
		}
		return newData
	}
	useImperativeHandle(ref, () => ({
		getData: onSubmit,
	}))

	return (
		<div className={styles.addPlan}>
			<Collapse
				defaultActiveKey={['1', '2', '3']}
				ghost
				expandIconPosition="end"
				collapsible="header"
			>
				<Panel header={customizeHeader('参与人')} key="1" forceRender>
					<ParticipantsTable
						type="add"
						data={dataList}
						setDataList={setDataList}
					/>
				</Panel>
				{startDate && 
					<Panel header={customizeHeader('盘点清单')} key="2" forceRender>
						<Form
							form={form}
							name="basic"
							layout="horizontal"
							labelCol={{flex: '140px'}}
							labelAlign="right"
							labelWrap
							autoComplete="off"
						>
							<Row gutter={12}>
								<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
									<Form.Item
										label="盘点表选择"
										name="stocktakeId"
										rules={[{required: true}]}
									>
										<Select
											showSearch
											placeholder="请选择"
											optionFilterProp="name"
											onChange={(value, key: any) => {
												form?.setFieldsValue({
													stocktakeType: key?.type,
												})
												setPlanId(value)
											}}
											fieldNames={{
												value: 'id',
												label: 'name',
											}}
											options={stocktakeList}
										/>
									</Form.Item>
								</Col>
								<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
									<Form.Item
										label="盘点类型"
										name="stocktakeType"
									>
										<Select
											disabled
											placeholder="请选择"
											options={[
												{value: 1, label: '全盘'},
												{value: 2, label: '抽盘'},
											]}
										/>
									</Form.Item>
								</Col>
							</Row>
						</Form>
						{planId ? (
							<Table
								scroll={{x: 5000}}
								loading={loading}
								columns={columns}
								dataSource={dataSource}
								bordered
							/>
						) : (
							''
						)}
					</Panel>
				}
				
				<Panel
					header={customizeHeader('盘点反馈附件')}
					key="3"
					forceRender
				>
					<AttachmentTable
						type="add"
						attachmentData={attachmentData}
						setAttachmentData={setAttachmentData}
					/>
				</Panel>
			</Collapse>
		</div>
	)
}

export default forwardRef(addPlan)
